package com.qiankan.qmsj.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.UserInfo;
import com.qiankan.qmsj.db.UserDBHelper;
import com.qiankan.qmsj.entity.Labels;
import com.qiankan.qmsj.entity.Product;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.utils.ColorUtils;
import com.qiankan.qmsj.utils.StringUtils;
import com.xingchen.AlertDialog;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ProductDetailActivity extends BaseActivity {
    @BindView(R.id.left)
    ImageView mProductImg;
    @BindView(R.id.tv_loanTitle)
    TextView mProductName;
    @BindView(R.id.tv_tip)
    TextView mProductTip;
    @BindView(R.id.ll_label)
    LinearLayout mProductLabel;
    @BindView(R.id.tv_applySuccess)
    TextView mTvSuccess;
    @BindView(R.id.tv_comment)
    TextView mTvComment;
    @BindView(R.id.tv_introduce)
    View mPreView;
    @BindView(R.id.tv_text)
    TextView mText;
    @BindView(R.id.rb_synthesize)
    RatingBar mRbSynthesize;
    @BindView(R.id.tv_synthesize)
    TextView mTvSynthesize;
    @BindView(R.id.tv_userSatisfy)
    TextView mTvSatisfy;
    @BindView(R.id.tv_loanSpeed)
    TextView mTvSpeed;
    @BindView(R.id.tv_loanRate)
    TextView mTvRate;
    @BindView(R.id.btn_comment)
    Button mBtnComment;
    private Product product;

    public static Intent newIntent(Context context, Product product) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra("product", product);
        return intent;
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLoadingDialog();
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", product.getId());
        APIHub.getsInstance().getBaseService().getProductDetail(param).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                dismissLoadingDialog();
                Result result = response.body();
                if (result.getCode().equals("200")) {
                    product = new Gson().fromJson(result.getData(), Product.class);
                    initAllMembersView(null);
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                dismissLoadingDialog();
            }
        });
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        mPreView.setSelected(true);
        /*CharSequence charSequence;
        String content = "本月已成功申请 <font color=\"#FF0000\">" + 100 + "</font>人";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            charSequence = Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY);
        } else {
            charSequence = Html.fromHtml(content);
        }
        mTvSuccess.setText(charSequence);*/
        product = (Product) getIntent().getSerializableExtra("product");
        if (product == null) {
            return;
        }
        AsyncLoadImage.loadImage(product.getIcon(), mProductImg, R.mipmap.ic_launcher);
        mProductName.setText(product.getName());
        mProductTip.setText(product.getIntro());
        String discussNum = TextUtils.isEmpty(product.getDiscussnum()) ? "0" : product.getDiscussnum();
        StringUtils.setTVColor("本月已成功申请" + StringUtils.convertNum(product.getApplynum()) + "人", '请', '人', getResources().getColor(R.color.themeOrange), mTvSuccess);
        StringUtils.setTVColor("评论" + StringUtils.convertNum(discussNum) + "次", '论', '次', getResources().getColor(R.color.themeOrange), mTvComment);
        mBtnComment.setText("评论(" + StringUtils.convertNum(discussNum) + ")");
        mText.setText(product.getIntroduce().replace("\\r\\n", "\r\n"));
        try {
            mRbSynthesize.setRating(Float.parseFloat(product.getGrade()));
        } catch (Exception e) {
        }
        if (!TextUtils.isEmpty(product.getGrade())) {
            mTvSynthesize.setText(product.getGrade() + "分");
        }
        if (!TextUtils.isEmpty(product.getExperience())) {
            mTvSatisfy.setText(product.getExperience() + "分");
        }
        if (!TextUtils.isEmpty(product.getUndersigned())) {
            mTvSpeed.setText(product.getUndersigned() + "分");
        }
        if (!TextUtils.isEmpty(product.getRatesign())) {
            mTvRate.setText(product.getRatesign() + "分");
        }
        mProductLabel.removeAllViews();
        for (Labels label : product.getLabels()) {
            TextView textView = new TextView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 10, 0);
            textView.setPadding(5, 1, 5, 1);
            textView.setTextSize(12);
            textView.setLayoutParams(lp);
            textView.setText(label.getName());
            textView.setTextColor(Color.parseColor("#FFFFFF"));
            try {
                textView.setBackgroundColor(Color.parseColor(ColorUtils.getHex(label.getColor())));
            } catch (Exception e) {

            }
            mProductLabel.addView(textView);
        }
    }

    @OnClick(R.id.tv_introduce)
    public void onClickIntroduce(View view) {
        mPreView.setSelected(false);
        mPreView = view;
        view.setSelected(true);
        mText.setText(product.getIntroduce().replace("\\r\\n", "\r\n"));
    }

    @OnClick(R.id.tv_condition)
    public void onClickCondition(View view) {
        mPreView.setSelected(false);
        mPreView = view;
        view.setSelected(true);
        mText.setText(product.getCondition().replace("\\r\\n", "\r\n"));
    }

    @OnClick(R.id.tv_material)
    public void onClickMaterial(View view) {
        mPreView.setSelected(false);
        mPreView = view;
        view.setSelected(true);
        mText.setText(product.getMaterials().replace("\\r\\n", "\r\n"));
    }

    @OnClick(R.id.btn_comment)
    public void onClickCommend(View view) {
        startActivity(CommentActivity.newIntent(this, product));
    }

    @OnClick(R.id.btn_borrow)
    public void onClickBorrow(View view) {
        UserInfo userInfo = UserDBHelper.getInstance(this).getUserInfo();
        if (userInfo == null) {
            Intent intent = new Intent(this, LogInActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (TextUtils.isEmpty(userInfo.getName()) || TextUtils.isEmpty(userInfo.getIdcard()) || TextUtils.isEmpty(userInfo.getPhone())) {
            showDialog();
        } else {
            Map<String, String> param = new HashMap<String, String>();
            param.put("user", userInfo.getId());
            param.put("product", product.getId());
            APIHub.getsInstance().getBaseService().reapply(param).enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    Result result = response.body();
                    if (result.getCode().equals("200")) {
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                }
            });
            Bundle bundle = new Bundle();
            bundle.putString("url", product.getLink());
            //分享相关
            bundle.putString("shareUrl", product.getLink());
            bundle.putString("title", product.getName());
            bundle.putString("content", product.getAdvertising());
            bundle.putString("sharePicUrl", product.getIcon());
            startActivity(WebActivity.newIntent(this, bundle));
        }
    }

    /*@OnClick(R.id.iv_share)
    public void onClickShare(View view) {
        Bundle bundle = new Bundle();
        bundle.putString("shareUrl", product.getLink());
        bundle.putString("title", product.getName());
        bundle.putString("content", product.getIntro());
        bundle.putString("sharePicUrl", product.getIcon());
        startActivity(MyShareActivity.newIntent(this, bundle));
    }*/

    @OnClick(R.id.iv_back)
    public void onClickBack(View view) {
        finish();
    }

    private void showDialog() {
        new AlertDialog(this).builder().setTitle("提示")
                .setMsg("请完善个人信息 ")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(PersionInfoActivity.newIntent(ProductDetailActivity.this));
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).show();
    }
}
